/*
 * @Description: 
 * @Author: 张民鸿
 * @Date: 2021-10-11 11:13:17
 * @FilePath: /cloud-register-business/Users/zhang/Desktop/zhang/Cloud-Registration-Desk/src/components/PrivateComponent/index.tsx
 * @LastEditTime: 2021-10-17 09:52:53
 * @LastEditors: MelodyJerry
 */
import React, { useEffect } from 'react';
import { connect, useDispatch } from 'react-redux';
import { Redirect } from 'react-router';
import { getPermissions } from '~/apis/login';
import { SAVE_PERMISSIONS } from '~reducers/common';


function PrivateComponent(props: any) {
    const dispatch = useDispatch()
    useEffect(() => {
        const { loginInfo, permissions } = props;
        if (!loginInfo) return;
        if (!permissions || !permissions.length) {
            getPermissionsApi()
        }
    }, [])
    async function getPermissionsApi() {
        let res = await getPermissions()
        dispatch({ type: SAVE_PERMISSIONS, data: res.data })
    }
    return (
        props.loginInfo ? props.children : <Redirect to="/login" />
    )

}

export default connect((state: any) => {
    const { loginInfo, permissions } = state.common;
    return {
        loginInfo,
        permissions
    }
})(PrivateComponent)